<?php
namespace Home\Logic;

class GoodsLogic {
	
	/**
	 * 计算商品运费
	 * @param $goods 商品信息(其中模板id必须) array('tplId'=>1201, ... ...)
	 * @param $locCode 配送位置 (省份代码)
	 * @param $quantity 商品数量 
	 * @return 
	 * array(
	 * 	 '1' => 20.5, // 快递
	 *   '2' => 45.7, // ems
	 *   '3' => 78.9 // 平邮
	 *   // ... ... ---省略DeliveryModel中定义的其它运送方式
	 * )
	 */
	public static function calcDeliveryFee( $goods, $locCode = '', $quantity = 0 ) {
		$result = array();
		$tplId = $goods['tplId']; // 模板id
		$configList = M("DeliveryTpl a")->join("__DELIVERY_TPL_CONFIG__ b on a.id=b.tpId")->where(array('a.id'=>$tplId))->field("b.typeId,b.config,b.selected")->select(); // 物流配置列表
		foreach ( $configList as &$v ) {
			$config = $v['config'] = unserialize($v['config']);
			if ( $config['enabled'] ) {
				$special = $config['special']; // 特殊配置 
				unset($config['special']);
				$default = $config; // 默认配置
				/* 使用默认或特殊配置 */
				$start = $default['start'];
				$postage = $default['postage'];
				$plus = $default['plus'];
				$postageplus = $default['postageplus'];
				if ( $special ) {
				    foreach ( $special as $v0  ) {
				        if ( in_array( $locCode, $v0['provCodes']) ) {
				            $start = $v0['start'];
				            $postage = $v0['postage'];
				            $plus = $v0['plus'];
				            $postageplus = $v0['postageplus'];
				            break;
				        }
				    }
				}
				/* 计算运费 */
				$unit = $quantity; // 按数量计算
				$realPostage = 0;
				if ( $quantity <= $start ) {
					$realPostage = $postage;
				} else {
					$realPostage = $postage + ceil(($unit - $start) / $plus)*$postageplus;
				}
				$result[$config['deliveryId']] = $realPostage; 
			}
		}
		return $result;
	}
	
}